/**
 * 一口价管理-城市配置
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */
layui.define(['form', 'layedit', 'laydate', 'laytpl', 'table'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;

    let status = true;

    // 省市区县下拉框联动
    zmnPage.laySelectLinkage(form, "/area/listCityList.action", "provinceId", "cityId");

    form.render(null, "zmn-oneprice-city-form");


    $("#deposit").val(json.item.deposit / 100)
    $("#depositDeductionAmount").val(json.item.depositDeductionAmount / 100)

    if (zmnUtil.isNotNull(json.item.depositStatus)) {
        if (json.item.depositStatus === 2) {
            $("#depositBlock").show();
        } else {
            status = false;
        }
    }

    if (json.item.payType == 1) {
        $("#setDeposit").show();
        if (json.item.depositStatus == 2) {
            $("#depositBlock").show();
        }
    }

    form.on('radio(depositStatus)', function (data) {
        if (data.value == 2) {
            $("#depositBlock").show();
            status = true;
        } else {
            $("#depositBlock").hide();
            status = false;
        }
    });
    form.on('radio(depositDeductionStatus)', function (data) {
        if (data.value == 2) {
            $("#depositDeductionAmountBlock").show();
        } else {
            $("#depositDeductionAmountBlock").hide();
        }
    });

    form.on('radio(payType)', function (data) {
        if (data.value == 1) {
            $("#setDeposit").show();
            status = true;
        } else {
            $("#setDeposit").hide();
            status = false;
        }
    });

    zmnLayUtil.layFormVerify(form);

    // 自定义验证规则
    form.verify({
        payType: function (value) {
            var val = $("input[name='payType']:checked").val();
            return val == null ? "请选择支付方式" : "";
        },
        status: function (value) {
            var val = $("input[name='status']:checked").val();
            return val == null ? "请选择状态" : "";
        },
        maxSix: function (value) {
            if (zmnUtil.isNull(value) || value == "") {
            } else {
                if (status) {
                    if (!/^[0-9]+(.[0-9]{1,2})?$/.test(value)) {
                        return '请输入1-100的数字，支持两位小数!';
                    }
                    if (value > 100 || value < 1) {
                        return '请输入1-100的数字，支持两位小数!';
                    }
                }
            }
        }
    });
    // 提交
    form.on('submit(zmn-oneprice-city-form-submit)', function (obj) {
        var data = obj.field;

        let cityList = [];
        $('.cityprice').each(function (index, obj) {
            cityList.push($(obj).attr('value'));
        })
        if (cityList.length == 0) {
            layer.alert("请选择城市!");
            return false;
        }
        data.cityList = cityList;

        if (data.type == 1 && !data.payType) {
            layer.msg("请设置支付方式!", {"icon": 2});
            return false;
        }
        if (data.payType == 1 && !data.depositStatus) {
            layer.msg("请设置是否设置定金!", {"icon": 2});
            return false;
        }

        // "下单时必须支付"，“设置定金”，定金必填
        if (data.payType == 1 && data.depositStatus != 1 && data.depositStatus != 2){
            layer.msg("请选择设置定金选项!", {"icon": 2});
            return false;
        }
        if (data.payType == 1 && data.depositStatus == 2) {
            if (!data.deposit || data.deposit == '') {
                layer.msg("请设置定金!", {"icon": 2});
                return false;
            }
            data.deposit = data.deposit >= 100 ? data.deposit : data.deposit * 100
        } else {
            data.deposit = null;
            data.depositStatus = 1
        }

        if (data.payType == 1 && data.depositStatus == 2 && data.depositDeductionStatus != 1 && data.depositDeductionStatus != 2){
            layer.msg("请选择设置定金抵扣选项!", {"icon": 2});
            return false;
        }
        // "下单时必须支付"，“设置定金”，定金抵扣必填
        if (data.payType == 1 && data.depositStatus == 2 && data.depositDeductionStatus == 2) {
            if (!data.depositDeductionAmount || data.depositDeductionAmount == '') {
                layer.msg("请设置定金抵扣金额!", {"icon": 2});
                return false;
            }
            if (!/^[0-9]+(.[0-9]{1,2})?$/.test(data.depositDeductionAmount)) {
                layer.msg("定金抵扣金额必须为数字，支持两位小数!", {"icon": 2});
                return false;
            }
            let deposit = data.deposit / 100;
            if (data.depositDeductionAmount <= deposit) {
                layer.msg("定金抵扣金额必须需在" + deposit + " ~ " + (deposit * 10) + "之间!", {"icon": 2});
                return false;
            }
            if (data.depositDeductionAmount > deposit * 10){
                layer.msg("定金抵扣金额必须需在" + deposit + " ~ " + (deposit * 10) + "之间!", {"icon": 2});
                return false;
            }
            data.depositDeductionAmount = data.depositDeductionAmount * 100
        } else {
            data.depositDeductionAmount = null;
            data.depositDeductionStatus = 1
        }

        saveData(data);
        return false;
    });

    function saveData(data) {
        var url = "/pilot/city/addEdit.action";
        zmnLayUtil.ajaxSimpleJson(url, data, null, function (res) {
            if (res.status == 200) {
                if (json.item.relationId != null && json.item.relationId > 0) {
                    layer.msg("修改成功", {"icon": 1});
                    return false;
                }
                location.href = '/pilot/channel/price/serviceCategory.action?configId=' + res.data + '&type=2&showType=2'
            } else {
                layer.msg("保存失败", {"icon": 2});
            }
        });
    }

    if (json.item.relationId) {
        addCity(json.item.provinceId, json.item.cityId, json.item.provinceName, json.item.cityName);
    }

    $('#addCity').click(function () {
        let provinceId = $('#provinceId').val();
        let cityId = $('#cityId').val();
        let provinceName = $('select[name="provinceId"] option:selected').text();
        let cityName = $('select[name="cityId"] option:selected').text();
        let type = $('#type').val();

        var url = '/pilot/city/checkCity';
        zmnLayUtil.ajaxSimpleUE(url, {provinceId: provinceId, cityId: cityId, type: type}, null, function (resp) {
            console.log(resp);
            if (resp.status == 200) {
                addCity(provinceId, cityId, provinceName, cityName);
            } else {
                layer.alert(resp.message);
            }
        });

        return false;
    });

    function addCity(provinceId, cityId, provinceName, cityName) {
        if (zmnUtil.isEmptyNull(provinceId)) {
            provinceId = 0;
        }
        if (zmnUtil.isEmptyNull(cityId)) {
            cityId = 0;
        }
        let flag = false;
        let checkMsg = "当前城市已存在！";
        $('.cityprice').each(function (index, obj) {
            var cityValue = $(obj).attr('value');
            var split = cityValue.split("-");
            if (cityValue == provinceId + "-" + cityId || (split[0] == provinceId && (split[1] == 0 || cityId == 0))) {
                flag = true;
                if (cityValue == provinceId + "-" + cityId) {

                } else if (split[1] == 0) {
                    checkMsg = "父级城市已存在！";
                } else if (cityId == 0) {
                    checkMsg = "子级城市已存在！";
                }
                return false;
            }
        });

        if (flag) {
            layer.alert(checkMsg);
            return;
        }

        let closeBtn = json.isDetail ? '' : '<i style="font-style: normal;margin-left: 10px;cursor: pointer;">X</i>';

        if ((provinceId == 0 || provinceId == '' || provinceId == null) && (cityId == 0 || cityId == '' || cityId == null)) {
            layer.alert("请选择省份！");
        } else if (cityId == 0 || cityId == '' || cityId == null) {
            $('#addCityDiv').append('<span class="cityprice" value=' + provinceId + '-' + 0 + ' style="display: inline-block;width: auto;border: 1px solid #ccc;border-radius: 10px;padding: 5px 20px; margin-right: 5px;tmargin-bottom: 5px;background-color: #009688;color:#fff;">' + provinceName + closeBtn + '</span>');
        } else {
            $('#addCityDiv').append('<span class="cityprice" value=' + provinceId + '-' + cityId + ' style="display: inline-block;width: auto;border: 1px solid #ccc;border-radius: 10px;padding: 5px 20px; margin-right: 5px;tmargin-bottom: 5px;background-color: #009688;color:#fff;">' + cityName + closeBtn + '</span>');
        }
    }

    $('#addCityDiv').on('click', 'span i', function () {
        $(this).parent().remove();
        return false;
    });


    //类似C#的字符串format
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/\{(\d+)\}/g, function (m, i) {
            return args[i];
        });
    };

    let logTable = {"code": 0, "msg": "", "count": json.totalCount, "items": json.items};
    let cols = [
        [{
            field: 'createTime', title: '操作时间', align: 'center', templet: function (row) {
                return zmnUtil.createTime(row.createTime);
            }
        },
            {field: 'abutmenter', title: '操作人', align: 'center'},
            {field: 'content', title: '操作内容', align: 'center'}
        ]
    ];
    if (json.item.relationId === null) {
        json.item.relationId = 0;
    }
    zmnLayUtil.layTableRender(table, cols, "zmn-list-city-price-log-table",
        logTable, "/pilot/city/listCityPriceLog.action?relationId=" + json.item.relationId);

    exports('pilot_city_edit', {});
});
